import pygame
import sys
import g
from character import Ken
import net
from util import *
import content
from game import Game

class ClientGame(Game):
	def __init__(self, zoom = 2):
		Game.__init__(self, zoom)
		self.netServer = None
		self.netClient = None

		self.preGameFont = pygame.font.SysFont(None, 36)

	def connect(self, addr, port = None):
		self.drawCenterText("Connecting...")
		if port is None:
			self.netClient = net.Client(addr)
		else:
			self.netClient = net.Client(addr, port)
		self.netClient.connect()

	def drawCenterText(self, text):
		self.screen.fill( (0,0,0) )
		t = self.preGameFont.render(text, False, (255,255,255))
		self.screen.blit(t, (self.width/2 - t.get_width() / 2, self.height / 2 - t.get_height() / 2))
		pygame.transform.scale(self.screen, (self.width * self.zoom, self.height * self.zoom), self._screen)
		pygame.display.update()

	def preGameRun(self):
		self.drawCenterText("Waiting for players...")
		while len(self.chars) < 2:
			self.netClient.update(self)
			for evt in pygame.event.get():
				if evt.type == pygame.QUIT:
					sys.exit()
					
		self.objs.extend(self.chars)

	def setupLocalCharacter(self):
		self.localChar.bindings = {
			pygame.K_u : "lP",
			pygame.K_i : "mP",
			pygame.K_o : "hP",
			pygame.K_j : "lK",
			pygame.K_k : "mK",
			pygame.K_l : "hK"
		}
		self.localChar.directionKeys = {
			"U" : pygame.K_w,
			"D" : pygame.K_s,
			"L" : pygame.K_a,
			"R" : pygame.K_d
		}
		self.localChar.client = True
		self.localChar.initialize()

	def setupNetCharacter(self):
		self.netChar.initialize()
		
	def killObject(self, obj):
		self.objsDel.append(obj)

	def initialize(self):
		pass

	def netUpdate(self):
		self.netClient.update(self)

	def handleKeyDown(self, key):
		self.localChar.keyPress(key)

def runGame(args):
	gGame = ClientGame(2)
	g.gGame = gGame
	content.loadContent()
	gGame.initialize()
	if len(sys.argv) == 1:
		gGame.connect(args[0])
	elif len(sys.argv) == 2:
		gGame.connect(args[0], int(args[1]))
	gGame.run()

if __name__ == "__main__":
	runGame(sys.argv[1:])

